﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsMessageGlobal.Funcs;

namespace WindowsFormsMessageGlobal.UI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonSubMessage_Click(object sender, EventArgs e)
        {
            MessageManager.Instance.MessageReceived += Instance_MessageReceived;
        }

        private void textAppendText(TextBox textBox,string str)
        {
            if(textBox.InvokeRequired)
            {
                textBox.Invoke(new Action(() => 
                {
                    if (textBox.Text.Length > 1000)
                        textBox.Text = "";
                    textBox.AppendText(str);
                }));                
            }
            else
            {
                if (textBox.Text.Length > 1000)
                    textBox.Text = "";
                textBox.AppendText(str);
            }
        }

        private void Instance_MessageReceived(Funcs.Message obj)
        {
            if (textBox1 != null && !textBox1.IsDisposed)
            {
                textAppendText(textBox1, obj.Content + Environment.NewLine);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageManager.Instance.MessageReceived += Instance_MessageReceived;
        }
    }
}
